package sanrenxing.foreStudentGrade.servlet;

import com.google.gson.Gson;
import sanrenxing.foreStudentGrade.dao.StudentGradeDao;
import sanrenxing.foreStudentGrade.dao.impl.StudentGradeDaoImpl;
import sanrenxing.foreStudentGrade.domain.StudentGrade;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @date 2020/10/14 18:53
 * 编辑者：邓志强
 * 功能：
 */
@WebServlet("/ForeStudentGradeServlet")
public class ForeStudentGradeServlet extends HttpServlet {
    //创建数据层对象
    StudentGradeDao sgd=new StudentGradeDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求字符集
        req.setCharacterEncoding("utf-8");
        //设置响应字符集和内容类型
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        //接收来自客户端方法信息
        String method=req.getParameter("method");
        if (method.equals("findGrade")){
            this.findGrade(req,resp);
        }

    }

    /**
     * 查询成绩
     * @param req
     * @param resp
     */
    private void findGrade(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //创建输出流
        PrintWriter out=resp.getWriter();
        //通过session拿到学员编号
        HttpSession session=req.getSession();
        String stuId=(String) session.getAttribute("stuId");
        //调用数据层代码，查询对应学员成绩
        List<StudentGrade> studentGradeList=sgd.findGrade(stuId);
        //创建map集合保存数组便于序列化
        Map<String,Object> map=new HashMap<>();
        map.put("data",studentGradeList);
        map.put("code",0);
        map.put("count",100);
        Gson gson=new Gson();
        //将成绩对象序列化成json数据
        String json=gson.toJson(map);
        if (json!=null){
            out.print(json);
        }else{
            out.print("no");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
